// 封装axios
// 实例化  请求拦截器 响应拦截器

import axios from 'axios'
import { getToken } from './token'
import { history } from './history'
import { message } from 'antd'
console.log(process.env)
const http = axios.create({
  baseURL: process.env.REACT_APP_BASE_API, // url = base url + request url
  // baseURL: '/api',
  timeout: 20000, // request timeout
})
const httpXp = axios.create({
  baseURL: process.env.REACT_APP_BASE_XP,
  timeout: 20000, // request timeout
})
// 添加请求拦截器
http.interceptors.request.use((config) => {
  // if not login add token
  const token = getToken()
  if (token) {
    config.headers.token = token
  }
  return config
}, (error) => {
  return Promise.reject(error)
})

// 添加响应拦截器
http.interceptors.response.use((response) => {
  // 文件类型
  if (response.config.responseType === 'blob') return Promise.resolve(response.data)
  if (response.config.url.search('/xp/') !== -1) return Promise.resolve(response.data)

  if (response.data.code === 0) {
    return response.data
  } else {
    switch (response.data.code) {
      case -1:
        message.error(response.data.msg || '接口异常')
        break
      case 500:
        message.error(response.data.msg)
        return Promise.resolve(response.data)
      case 10002:  // 先设定需要重新登录的状态码
        // toLogin()
        break
      default: break
    }
    return Promise.reject(response.data)
  }
}, (error) => {
  let msg = error.message
  if (msg === 'Network Error') {
    msg = '后端网络故障'
  } else if (msg.includes('timeout')) {
    msg = '接口请求超时'
  } else if (msg.includes('Request failed with status code')) {
    msg = '接口' + msg.substr(msg.length - 3) + '异常'
  }
  message.error(msg)
  if (error.response.status === 401) {
    // 跳回到登录 reactRouter默认状态下 并不支持在组件之外完成路由跳转
    // 需要自己来实现
    history.push('/login')
  }
  return Promise.reject(error)
})
const baseUrlWs = process.env.REACT_APP_BASE_WS
export {
  http,
  baseUrlWs,
  httpXp
}